import CONFIG from 'constants/config';

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\\+\\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\\+~%\\/.\w-_]*)?\??(?:[-\\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g;

export function isUrl(path) {
  return reg.test(path);
}

function getRelation(str1, str2) {
  if (str1 === str2) {
    console.warn('Two path are equal!'); // eslint-disable-line
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
  } else if (arr1.every((item, index) => item === arr2[index])) {
    return 2;
  }
  return 3;
}

function getRenderArr(routes) {
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
    let isAdd = false;
    // 是否包含
    isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
    // 去重
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path
  );
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
  const renderRoutes = renderArr.map(item => {
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
      exact,
      ...routerData[`${path}${item}`],
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}

/**
 * 时间戳格式化
 * @param {number} ts 单位是秒
 * @param {string} separator
 * @param {boolean} onlyDate
 */
export function timestamp2date(ts, separator = '-', onlyDate = true) {
  const date = new Date(ts * 1000);
  let str = date.getFullYear() + separator;
  str += (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + separator;
  str += date.getDate() + ' ';

  if (!onlyDate) {
    str += date.getHours() + ':';
    str += date.getMinutes() + ':';
    str += date.getSeconds();
  }

  return str;
}

/**
 * 从二维数组中删除指定对象的元素
 * @param {any} arr
 * @param {object} item
 */
export function arrayRemoveItem(arr, target) {
  var index = arr.findIndex(item => {
    return target.id === item.id;
  });

  if (Number.isInteger(index)) {
    arr.splice(index, 1);
  }

  return arr;
}

export function getAbsoluteStaticUrl(uri) {
  if (!uri) {
    return 'image_not_found.png';
  }

  if (/^https?:/i.test(uri)) {
    return uri;
  }

  return CONFIG.STATIC_ROOT + uri;
}

/**
 *
 * @param {Array} loadingArr Reducer loading数组
 * @param {String} action 请求动作
 */
export function isLoading(loadingArr, action) {
  return Boolean(loadingArr[action + '_loading']);
}

/**
 * 两个数字（字符串）比较
 * @param {mix} num1 数字
 * @param {mix} num2 数字
 */
export function isEqualWithNumber(num1, num2) {
  return Number(num1) === Number(num2);
}

/**
 *
 * @param {Array} arr 数组
 * @param {Number} index1 元素下标
 * @param {Number} index2 元素下标
 */
export function switchElePosition(arr, index1, index2) {
  const tmp = arr[index1];
  arr[index1] = arr[index2];
  arr[index2] = tmp;
  return arr;
}
